package com.shelpe.services.sinbad;

import java.util.Collections;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.cloud.netflix.metrics.atlas.AtlasTagProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableTransactionManagement
@MapperScan("com.shelpe.services.sinbad.dao")
@EnableJpaRepositories(basePackages="com.shelpe.services.sinbad.repository.jpa")
public class DataBaseConfig {

	@Bean
    public DataSource dataSource(DataSourceProperties props) {
		DruidDataSource ds = new DruidDataSource();
		if(props != null){
			ds.setDriverClassName(props.getDriverClassName());
			ds.setUrl(props.getUrl());
			ds.setUsername(props.getUsername());
			ds.setPassword(props.getPassword());
		}
        return ds;
    }
	
	@Bean
	public AtlasTagProvider atlasCommonTags(@Value("${spring.application.name}")final String appName){
		return new AtlasTagProvider(){
			@Override
			public Map<String, String> defaultTags() {
				return Collections.singletonMap("atlas", appName);
			}
			
		};
	}
 
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception {
 
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(ds);
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
 
        sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:/mybatis-config.xml"));
        
        sqlSessionFactoryBean.setMapperLocations(resolver
                .getResources("classpath:/sqlmaps/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }
	
}
